package net.thxjj.adminServer.service.impl;

import cmcciot.onenet.nbapi.sdk.api.online.CreateDeviceOpe;
import cmcciot.onenet.nbapi.sdk.api.online.GetDeviceDetailOpe;
import cmcciot.onenet.nbapi.sdk.api.online.GetDevicesOpe;
import cmcciot.onenet.nbapi.sdk.entity.CreateDevice;
import cmcciot.onenet.nbapi.sdk.entity.GetDevice;
import cmcciot.onenet.nbapi.sdk.entity.GetDeviceDetail;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctg.ag.sdk.biz.AepDeviceManagementClient;
import com.ctg.ag.sdk.biz.aep_device_management.CreateDeviceRequest;
import com.ctg.ag.sdk.biz.aep_device_management.CreateDeviceResponse;
import com.ctg.ag.sdk.biz.aep_device_management.QueryDeviceRequest;
import com.ctg.ag.sdk.biz.aep_device_management.QueryDeviceResponse;
import net.thxjj.adminServer.dao.DeviceDao;
import net.thxjj.adminServer.dao.ExcelDao;
import net.thxjj.adminServer.dao.ProductDao;
import net.thxjj.adminServer.entity.*;
import net.thxjj.adminServer.service.IExcelDeviceService;
import net.thxjj.adminServer.util.ImgUtil;
import net.thxjj.adminServer.util.ParameterMap;
import net.thxjj.adminServer.util.excel.PoiUtil;
import net.thxjj.adminServer.websocket.mq.JSONOneNet2DeviceUtil;
import net.thxjj.sitermodel.Device;
import net.thxjj.sitermodel.Product;
import net.thxjj.sitermodel.User;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ExcelDeviceService implements IExcelDeviceService {
    @Value("${upload.root.folder}")
    public String root_fold;

    @Value("${file.folder}")
    public String file_fold;

    @Autowired
    private ExcelDao excelDao;

    @Autowired
    private ProductDao productDao;


    @Autowired
    private DeviceDao deviceDao;

    @Override
    public Object excelImport(MultipartFile file, User user) {
        try {
            if(file!=null){
                String fileName = file.getOriginalFilename();
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                String freName = fileName.substring(0,fileName.lastIndexOf("."));
                String LastFileName = freName+System.currentTimeMillis()+suffixName;


                String suffix = StringUtils.substring(fileName, fileName.lastIndexOf(".") + 1);
                //根据上传的excel文件构造workbook实例，注意区分xls与xlsx版本对应的实例
                Workbook workbook = PoiUtil.getWorkbook(file, suffix);
                //读取上传上来的excel的数据到list<Product>中
                List<Device> products = PoiUtil.readExcelData(workbook);

                if(products.size()==0){
                    return ResponseModel.getModel(ResultEnum.FILE_CONTENT_IS_ERROR,null);
                }

                //插入excel到数据库
                ExcelReportBean excelReportBean = new ExcelReportBean();
                excelReportBean.setUserId(user.getUser_id()).setCreateTime(System.currentTimeMillis()).setFile("/upload/show"+file_fold+LastFileName);
                excelDao.insertExcel(excelReportBean);

                // excel文件上传后的路径
                String filePath = root_fold+file_fold;
                ImgUtil.createFileFold(filePath);
                File dest = new File(filePath + LastFileName);
                try {
                    file.transferTo(dest);
                    System.out.println("upload  success");
                }catch (IOException e) {
                    e.printStackTrace();
                    return ResponseModel.getModel(ResultEnum.FILE_UPLOAD_ERROR,null);
                }


                int success_result = 0;
                int failt_result = 0;
                List<ExcelResultBean> list = new ArrayList<>();
                for(int i=0;i<products.size();i++){
                    Device device = products.get(i);
                    String prodKey = device.getProdKey();
                    Product product = productDao.getProduct(prodKey);
                    if("aep".equals(product.getPlatform())){
                        AepDeviceManagementClient client = AepDeviceManagementClient.newClient()
                                .appKey(Const.APPKEY).appSecret(Const.APPSECRET)
                                .build();

                        CreateDeviceRequest request = new CreateDeviceRequest();
                        JSONObject param2 = new JSONObject();
                        param2.put("autoObserver",0);
                        JSONObject param = new JSONObject();
                        param.put("productId",product.getProdKey());
                        param.put("imei",device.getImei());
                        param.put("deviceName",device.getDeviceName());
                        param.put("operator","admin");
                        param.put("other",param2);
                        request.setParamMasterKey(product.getApiKey());	// single value
                        request.setBody(param.toJSONString().getBytes());	//具体格式见前面请求body说明
                        try {
                            CreateDeviceResponse createDeviceResponse = client.CreateDevice(request);
                            String body = new String(createDeviceResponse.getBody());
                            JSONObject jsonObject = JSON.parseObject(body);
                            int code = jsonObject.getIntValue("code");
                            String msg = jsonObject.getString("msg");
                            ExcelResultBean excelResultBean;
                            if(code==0){
                                String device_id = jsonObject.getJSONObject("result").getString("deviceId");
                                success_result++;
                                excelResultBean = new ExcelResultBean().setImei(device.getImei()).setResult(0).setReportId(excelReportBean.getId());
                                AepDeviceManagementClient client2 = AepDeviceManagementClient.newClient()
                                        .appKey(Const.APPKEY).appSecret(Const.APPSECRET)
                                        .build();

                                QueryDeviceRequest request2 = new QueryDeviceRequest();
                                request2.setParamMasterKey(product.getApiKey());	// single value
                                request2.setParamProductId(product.getProdKey());	// single value
                                request2.setParamDeviceId(device_id);
                                try {
                                    QueryDeviceResponse queryDeviceResponse = client2.QueryDevice(request2);
                                    String body2 = new String(queryDeviceResponse.getBody());
                                    JSONObject jsonObject2 = JSON.parseObject(body2);
                                    JSONObject result = jsonObject2.getJSONObject("result");
                                    Device ad = JSONObject.parseObject(result.toJSONString(),Device.class);
                                    ad.setProdKey(prodKey);
                                    ad.setCreateTime(System.currentTimeMillis());
                                    deviceDao.saveSingleDevice(ad);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                client2.shutdown();
                            }else {
                                failt_result++;
                                excelResultBean = new ExcelResultBean().setImei(device.getImei()).setResult(1).setReportId(excelReportBean.getId()).setReason(msg);
                            }
                            list.add(excelResultBean);
                        } catch (Exception e) {
                            e.printStackTrace();
                            failt_result++;
                            ExcelResultBean excelResultBean = new ExcelResultBean().setImei(device.getImei()).setResult(1).setReportId(excelReportBean.getId()).setReason("未知错误");
                            list.add(excelResultBean);
                        }

                        client.shutdown();
                    }else if("onenet".equals(product.getPlatform())){
                        CreateDevice createDevice =new CreateDevice();
                        CreateDeviceOpe createDeviceOpe = new CreateDeviceOpe(product.getApiKey());
                        JSONObject jsonObject = new JSONObject();
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put(device.getImei(),device.getImei());
                        jsonObject.put("title",device.getDeviceName());
                        jsonObject.put("protocol","LWM2M");
                        jsonObject.put("auth_info",jsonObject1);
                        JSONObject jsonResult = createDeviceOpe.operation(createDevice,jsonObject);
                        int code = jsonResult.getIntValue("errno");
                        String msg = jsonResult.getString("error");
                        ExcelResultBean excelResultBean;
                        if(code==0){
                            String device_id = jsonResult.getJSONObject("data").getString("device_id");
                            success_result++;
                            excelResultBean = new ExcelResultBean().setImei(device.getImei()).setResult(0).setReportId(excelReportBean.getId());
                            GetDeviceDetail getDeviceDetail = new GetDeviceDetail(device_id);

                            GetDeviceDetailOpe getDeviceDetailOpe = new GetDeviceDetailOpe(product.getApiKey());

                            JSONObject data  =  getDeviceDetailOpe.operation(getDeviceDetail,null).getJSONObject("data");
                            Device device1 =  JSONOneNet2DeviceUtil.getDeviceFrom(data);
                            device1.setDeviceId(device_id);
                            deviceDao.saveSingleDevice(device1);
                        }else {
                            failt_result++;
                            excelResultBean = new ExcelResultBean().setImei(device.getImei()).setResult(1).setReportId(excelReportBean.getId()).setReason(msg);
                        }
                        list.add(excelResultBean);
                    }else{
                        failt_result++;
                        ExcelResultBean excelResultBean = new ExcelResultBean().setImei(device.getImei()).setResult(1).setReportId(excelReportBean.getId()).setReason("错误的prod_key");
                        list.add(excelResultBean);
                    }
                }


                excelDao.insertExcelResults(list);

                ParameterMap parameterMap = new ParameterMap();
                parameterMap.put("success",success_result);
                parameterMap.put("failed",failt_result);
                parameterMap.put("report_id",excelReportBean.getId());
                return ResponseModel.getModel(ResultEnum.SUCCESS,parameterMap);

            } else {
                return ResponseEntity.status(500);
            }
        } catch (Exception e) {
            return ResponseModel.getModel(ResultEnum.FILE_UPLOAD_ERROR_ERROR_FORMAT,null);
        }
    }

    @Override
    public List<ExcelResultBean> getReportList(long reportId) {
        return excelDao.getReportList(reportId);
    }

    @Override
    public ExcelReportBean getReport(long reportId) {
        return excelDao.getReport(reportId);
    }
}
